<?php

namespace app\store\model;
use think\Model;
use think\Db;
use app\common\model\Menus as MenusModel;
use think\Request;
class Menus extends Model{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'type_text',
        'flag_text',
    ];

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $row->save(['weigh' => $row['id']]);
        });
    }
    /**
     * 定义栏目按钮
     * @param $data
     * @return bool
     */
    public function admin_menu($role_id=null, $pid, $with_self = false, $map = [])
    {
        $pid = intval($pid);

        if (1 != $role_id) {
            $condition = ['m.pid' => $pid];
            if ($with_self) {
                $condition['m.id'] = $pid;
                $condition['_logic'] = 'OR';
            }
            $map['_complex'] = $condition;
//            $map['m.display'] = 1;
            //为权限控制
            $map['status'] = 1;
            $map['a.role_id'] = $role_id;

            $menus = model()->table('__MENU__ m')
                ->join('__ADMIN_AUTH__ a on m.id=a.menu_id', 'LEFT')
                ->field('m.*')
                ->where($map)
                ->order('m.ordid,m.dialog DESC,m.id')->select();

        } else {
            $condition = ['pid' => $pid];
            if ($with_self) {
                $condition['id'] = $pid;
                $condition['_logic'] = 'OR';
            }
            $map['_complex'] = $condition;
//            $map['display'] = 1;
            $map['status'] = 1;

            //$menus = M("Menu")->where($map)->order('ordid,dialog desc,id')->select();
            $menus=Menus::all(function($query)use($pid){
               $query->where(['status'=>1,'pid'=>$pid]);
           });
        }

        return $menus;
    }

    public function sub_menu($role_id, $pid = '', $big_menu = false)
    {
        $array = $this->admin_menu($role_id, $pid, false);
        /*$numbers = count($array);
        if ($numbers==1 && !$big_menu) {
            return '';
        }*/
        //dump($array);
        return $array;
    }

    public function setFlagAttr($value, $data)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    /**
     * 读取分类类型
     * @return array
     */
    public static function getTypeList()
    {
        $typeList = config('site.categorytype');

        foreach ($typeList as $k => &$v)
        {
            $v = __($v);
        }
        return $typeList;
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getFlagList()
    {
        return ['hot' => __('Hot'), 'index' => __('Index'), 'recommend' => __('Recommend')];
    }

    public function getFlagTextAttr($value, $data)
    {
        $value = $value ? $value : $data['flag'];
        $valueArr = explode(',', $value);
        $list = $this->getFlagList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }

    /**
     * 读取分类列表
     * @param string $type      指定类型
     * @param string $status    指定状态
     * @return array
     */
    public static function getCategoryArray($type = NULL, $status = NULL)
    {
        $list = collection(self::where(function($query) use($type, $status) {
            if (!is_null($type))
            {
                $query->where('type', '=', $type);
            }
            if (!is_null($status))
            {
                $query->where('status', '=', $status);
            }
        })->order('weigh', 'desc')->select())->toArray();
        return $list;
    }


        /* 获取菜单详情
        * @param $goods_id
        * @return null|static
        * @throws \think\exception\DbException
        */
    public static function detail($id)
    {
        return self::get($id);
    }

    /**
     * 编辑菜单
     * @param $data
     * @return bool
     */
    public function edit($data)
    {
        //$data['content'] = isset($data['content']) ? $data['content'] : '';
        //$data['wxapp_id'] = $data['spec']['wxapp_id'] = self::$wxapp_id;
        // 开启事务
        Db::startTrans();
        try {
            $this->allowField(true)->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }
    /**
     * 添加菜单
     * @param array $data
     * @return bool
     */
    public function add(array $data)
    {
        if (!isset($data['title']) || empty($data['index']) || empty($data['index'])) {
            $this->error = '参数不能为空';
            return false;
        }
       // dump($data);die;
        // 开启事务
        Db::startTrans();
        try {
            // 添加菜单
            $this->allowField(true)->save($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage();
            return false;
        }

    }
    /*
     * 删除菜单
     * */
    public function remove($id){

        Db::startTrans();
        try{
            //删除当前栏目
            $model=$this->get($id);
            $model->delete();
            //删除子集
            $model->destroy(['pid'=>$id]);
            Db::commit();
            return true;
        }catch (\Exception $e){
            //$error=$e->getMessage();
            Db::rollback();
            return false;

        }


    }




}